"""
程序主要逻辑部分
by LeeDvan
"""
from PyQt5.QtGui import QImageReader, QPixmap, QIcon, QImage, QColor, QImageWriter
from PyQt5.QtWidgets import QGraphicsPixmapItem, QGraphicsItem, QFileDialog


from GUI.MainWindow import MainWindow
from GUI.Widget.Canvas import ImageDialog
import GUI.Window.Dialog as Dialog
import App
import Processor
import Utility.path as Path

Window: MainWindow = None   # 主窗体


def init(window):
    global Window
    Window = window


def openImage(path):
    """
    open image file by path
    :param path: str
    :return:
    """
    reader = QImageReader()
    reader.setFileName(path)
    if reader.canRead():
        image = reader.read()
        info = {
            'title': Path.getName(path)
        }
        addImage(image, info)
    else:
        print('不能打开')


def newImage():
    """
    用新建图像窗口
    新建图片
    :return:
    """
    dialog = Dialog.NewImage(Window)
    if dialog.exec_():
        name = dialog.LineEdit_Name.text()
        width = int(dialog.LineEdit_Width.text())
        height = int(dialog.LineEdit_Height.text())
        color = dialog.selectedColor
        if width < 16:
            width = 16
        if height < 16:
            height = 16
        image = QImage(width, height, QImage.Format_RGB32)
        image.fill(color)
        info = {
            'title': name
        }
        addImage(image, info)


def addImage(image: QImage, info={}):
    """
    给当前图像工作窗体添加Image图片
    :param image:
    :param info: 信息
    :return:
    """
    win = Window
    imageWindow = win.currentImageWindow
    if not imageWindow:  # 没有打开图片
        imageWindow = win.newImageWindow(info)
    if not imageWindow.canvasSize:
        size = image.size()
        imageWindow.setCanvasSize(size)
        firstOpen = True
    else:
        firstOpen = False
    newLayer = imageWindow.addPixmapLayer(image)
    if firstOpen:
        imageWindow.imageLayer.setSelectedLayer(newLayer)


# 动作
def openFile():
    window = Window
    files = QFileDialog.getOpenFileName(window, '打开文件', './', 'Images (*.png *.xpm *.jpg)')
    imagePath = files[0]
    if imagePath != '':
        print(imagePath)
        App.openImage(imagePath)


def saveFile():
    """
    保存文件
    """
    window = Window
    fileName = QFileDialog.getSaveFileName(window, '保存图片', './untitled.png', 'Images (*.png *.xpm *.jpg)')
    if fileName[0] != '':
        imageWindow = window.currentImageWindow  # 当前图像工作窗体
        if imageWindow is not None:
            imageWindow.saveCanvas()
            writer = QImageWriter()
            writer.setFileName(fileName[0])
            writer.setQuality(100)
            # writer.setFormat('png')
            writer.write(imageWindow.image)
            print('保存图像', writer.errorString())


def transform():
    window = Window
    imageWindow = window.currentImageWindow
    imageWindow.addTransform()


def welcome():
    window = ImageDialog(Window, QPixmap(':/logo/welcome.png'))
    window.setWindowTitle('Welcome')
    window.show()

#           图层
def toGrayImage():
    """
    灰度图
    :return:
    """
    window = Window
    imageWindow = window.currentImageWindow
    image = imageWindow.currentLayer.image
    image = Processor.Image.toGrayImage(image)
    imageWindow.addPixmapLayer(image)


def reversePhase():
    """
    反相
    :return:
    """
    window = Window
    imageWindow = window.currentImageWindow
    layer = window.currentLayer
    if layer:
        image = layer.image
        image = Processor.Image.reversePhase(image)
        imageWindow.addPixmapLayer(image)


def threshold():
    """
    阈值
    :return:
    """
    window = Window
    layer = window.currentLayer
    if layer:
        Processor.newThreshold(window)


def histogram():
    """
    直方图
    :return:
    """
    window = Window
    layer = window.currentLayer
    if layer:
        Processor.newHistogram(window)


def equalizeHist():
    """
    直方图均衡
    :return:
    """
    window = Window
    layer = window.currentLayer
    if layer:
        Processor.newEqualizeHist(window)


def contrast():
    """
    对比度
    :return:
    """
    window = Window
    layer = window.currentLayer
    if layer:
        Processor.newContrast(window)


def gasussNoise():
    """
    高斯噪声
    :return:
    """
    window = Window
    layer = window.currentLayer
    if layer:
        Processor.noise.newGasussNoise(window)


def spNoise():
    """
    椒盐噪声
    :return:
    """
    window = Window
    layer = window.currentLayer
    if layer:
        Processor.noise.newSPNoise(window)